package com.hs.order.consumer;


import com.hs.order.constant.OrderConstant;
import com.hs.order.dto.OrderDto;
import com.hs.order.exception.Asserts;
import com.hs.order.service.IOrdersService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * @author Bai Dingkun
 * @date 2022-07-16
 * @desc
 */
@Slf4j
@Component
public class OrderConsumer {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 消息最大重试次数
     */
    private static final int MAX_RETRIES = 3;

    /**
     * 重试间隔(秒)
     */
    private static final long RETRY_INTERVAL = 10;


    @RabbitListener(queues = "ttl-order-queue",concurrency = "5-10")
    public void consumer(@Payload OrderDto orderDto, Channel channel, Message message) throws IOException, InterruptedException {

        log.info("尝试消费队列中的消息 {}",orderDto);

        // 重试次数
        int retryCount = 0;
        boolean success = false;
        // 消费失败并且重试次数<=重试上限次数
        while (!success && retryCount < MAX_RETRIES) {
            retryCount++;
            // 具体业务逻辑
            //  获取订单认领状态
            String key = "tempOrder:" + "roadId:" + orderDto.getRoadId() + ":berthId:" + orderDto.getBerthId();
            Integer status = (Integer) redisTemplate.opsForHash().get(key, "status");
            success = status == OrderConstant.ORDER_STATUS_CLAIM;
            // 如果失败则重试
            if (!success) {
                String errorTip = "第" + retryCount + "次消费失败" +
                        ((retryCount < 6) ? "," + RETRY_INTERVAL + "s后重试" : ",进入死信队列");
                log.error(errorTip);
                Thread.sleep(RETRY_INTERVAL * 1000);
            }
        }
        if (success) {
            // 消费成功，确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("创建订单数据消费成功");
        } else {
            // 重试多次之后仍失败，进入死信队列
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            log.info("创建订单数据消费失败");
        }

        }

    }

